package com.example.lin.day10_17_bluetooth;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class BluetoothRVAdapter extends Adapter<BluetoothRVAdapter.BluetoothViewHolder> {

    private List<BluetoothDevice> devices;

    private Context context;

    public BluetoothRVAdapter(Context context) {
        this.context = context;
        devices = new ArrayList<>();
    }

    public List<BluetoothDevice> getDevices() {
        return devices;
    }

    public void setDevices(List<BluetoothDevice> devices) {
        this.devices = devices;
    }

    public void addDevice(BluetoothDevice device) {
        if (devices != null) {
            //判断 蓝牙设备已经显示,则不在添加
            for (BluetoothDevice d : devices) {
                if (d.getAddress().equals(device.getAddress())) {
                    return;
                }
            }
            devices.add(device);
            notifyDataSetChanged();//刷新适配器
        }
    }

    public void clears() {
        devices.clear();
        notifyDataSetChanged();
    }

    public static class BluetoothViewHolder extends RecyclerView.ViewHolder {

        ImageView iv_icon;
        TextView tv_name;

        public BluetoothViewHolder(View itemView) {
            super(itemView);
            iv_icon = itemView.findViewById(R.id.iv_icon);
            tv_name = itemView.findViewById(R.id.tv_name);
        }
    }


    @NonNull
    @Override
    public BluetoothViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new BluetoothViewHolder(LayoutInflater.from(context).inflate(R.layout.view_bluetooth_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull BluetoothViewHolder holder, final int position) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onItemClick(devices.get(position), v, position);
                }
            }
        });
        holder.tv_name.setText(devices.get(position).getName());
    }

    @Override
    public int getItemCount() {

        return devices == null ? 0 : devices.size();
    }


    private OnRVItemClickListener listener;

    public void setOnRVItemClickListener(OnRVItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnRVItemClickListener {
        void onItemClick(BluetoothDevice bluetoothDevice, View view, int position);
    }


}
